package wangchao.tools;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;

/**
 * Created by JMT-GJH on 2015/5/25.
 */
public class SignManageTool {
	
	protected final static Logger logger = LoggerFactory.getLogger(SignManageTool.class);
	
	/**
	 * 验证 验证摘要
	 * 
	 * @return
	 */
	public static boolean checkSign(String sign, Map<String, Object> map) {
		StringBuffer sbr = new StringBuffer();
		try {
			for (Entry<String, Object> entry : map.entrySet()) {
				sbr = sbr.append(entry.getKey() + "=" + entry.getValue()).append("&");
			}
		} catch (Exception e) {
			logger.error("验证摘要失败!", e);
		}
		String md5 = null;
		try {
			md5 = CreateMd5.getMD5(URLEncoder.encode(sbr.substring(0,sbr.length()-1).toString().trim(),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error("encode失败!", e);
		}
		return md5.equals(sign);
	}
	
	/**
	 * 构建sign
	 * 
	 * @return
	 */
	public static String structureSign(Map<String, Object> map) {
		StringBuffer sbr = new StringBuffer();
		try {
			for (Entry<String, Object> entry : map.entrySet()) {
				sbr = sbr.append(entry.getKey() + "=" + entry.getValue()).append("&");
			}
		} catch (Exception e) {
			logger.error("构建sign失败!", e);
		}
		String md5 = null;
		try {
			md5 = CreateMd5.getMD5(URLEncoder.encode(sbr.substring(0,sbr.length()-1).toString(),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error("encode失败!", e);
		}
		return md5;
	}
	
	/**
	 * 对传过来的json进行分解排序构建，返回sign未加密的Map
	 * @param json
	 * @return
	 */
	public static Map<String,Object> formSign(JSONObject json){
		Map<String,Object> map = new LinkedHashMap<String, Object>();
		Set<String> set = json.keySet();
		Iterator<String> iterator = set.iterator();
		List<String> strList = new ArrayList<String>();
		while(iterator.hasNext()){
			String it = iterator.next();
			strList.add(it);
		}
		Collections.sort(strList);
		for(String str : strList){
			map.put(str, json.getString(str));
		}
		return map;
	}
	
}
